package com.campus.client.view;

import com.campus.client.controller.ShopController;
import com.campus.common.vo.Product;
import com.campus.common.vo.User;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

public class ShopAdminFrame {

    private ShopController shopController;
    private VBox productListVBox; // 展示商品列表
    private Stage primaryStage;
    private String currentCategory = "全部"; // 当前选中的类别

    private Button backBtn;

    private User user=new User();
    public User getUser() {return user;}
    public void setUser(String Id,String password,String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
        //System.out.print("用户名"+this.user.getId());
    }


    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;

        // 初始化管理员专用 ShopController
        try {
            shopController = new ShopController(
                    new com.campus.client.net.ClientConnector("172.20.10.2", 8888)

            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        // ============ 主界面布局设计 ============
        // 使用BorderPane作为主布局
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        // 添加顶部标题栏+类别选择
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));
        headerBox.setSpacing(20); 
        
        Label titleLabel = new Label("商店系统 - 管理员版");
        titleLabel.getStyleClass().add("header-title");
        
        ComboBox<String> categoryCombo = new ComboBox<>();
        categoryCombo.getItems().addAll("全部", "食物", "饮料", "文具", "日用品");
        categoryCombo.setValue("全部");
        categoryCombo.setOnAction(e -> {
            currentCategory = categoryCombo.getValue();
            loadProducts(); // 切换类别时刷新
        });
        
        // 空白区域，用来推按钮到最右侧
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        
        // 添加导航按钮，可返回主界面
        backBtn = createStyledButton("返回主界面");
        backBtn.getStyleClass().add("nav-button");
        backBtn.setOnAction(e -> {
            try {
                back();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        
        headerBox.getChildren().addAll(titleLabel, categoryCombo, spacer, backBtn); 
        root.setTop(headerBox);

        // 创建内容区域，使用卡片式布局
        VBox contentBox = new VBox();
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));
        
        // ============ 顶部操作栏设计 ============
        // 顶部操作栏样式
        HBox topBar = new HBox();
        topBar.setAlignment(Pos.CENTER_LEFT);
        topBar.setSpacing(10);
        topBar.setPadding(new Insets(0, 0, 15, 0));
        
        Label sectionTitle = new Label("商品管理");
        sectionTitle.getStyleClass().add("section-title");
        
        // 按钮样式
        Button addBtn = createStyledButton("新增商品");
        addBtn.getStyleClass().add("primary-button");
        addBtn.setOnAction(e -> showAddProductDialog());
        
        topBar.getChildren().addAll(sectionTitle, addBtn);
        
        // ============ 商品列表区域设计 ============
        // 商品列表
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.getStyleClass().add("scroll-pane");
        productListVBox = new VBox(10);
        productListVBox.setPadding(new Insets(10));
        productListVBox.getStyleClass().add("content-area");

        scrollPane.setContent(productListVBox);
        scrollPane.setFitToWidth(true);
        
        contentBox.getChildren().addAll(topBar, scrollPane); 
        root.setCenter(contentBox);

        // 加载商品
        loadProducts();

        // ============ 场景与舞台设置 ============
        Scene scene = new Scene(root, 1000, 700);
        scene.getStylesheets().add(
                getClass().getResource("/css/style.css").toExternalForm()
        );
        primaryStage.setTitle("虚拟校园系统 - 商店管理");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    

    // ============ 工具方法设计 ============
    // 优化按钮创建方法
    private Button createStyledButton(String text) {
        Button button = new Button(text);
        button.getStyleClass().add("styled-button");
        return button;
    }
    
    // ============ 商品加载功能 ============
    // 加载所有商品
    private void loadProducts() {
        productListVBox.getChildren().clear();
        try {
            List<Product> products = shopController.getProducts();
            
            if (!"全部".equals(currentCategory)) {
                products = products.stream()
                        .filter(p -> p.getCategory().equals(currentCategory))
                        .collect(Collectors.toList());
            }
            if (products.isEmpty()) {
                Label emptyLabel = new Label("暂无商品，请点击「新增商品」添加");
                emptyLabel.getStyleClass().add("empty-label");
                productListVBox.getChildren().add(emptyLabel);
            } else {
                for (Product p : products) {
                    productListVBox.getChildren().add(createProductBox(p));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载商品失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    // ============ 单个商品卡片设计 ============
    // 商品卡片布局和样式
    private HBox createProductBox(Product p) {
        HBox box = new HBox(15);
        box.setPadding(new Insets(15));
        box.getStyleClass().add("product-card");
        box.setAlignment(Pos.CENTER_LEFT);

        // 图片区域
        VBox imageBox = new VBox(10);
        imageBox.setAlignment(Pos.TOP_CENTER);
        
        ImageView imageView = new ImageView();
        imageView.setFitWidth(120);
        imageView.setFitHeight(120);
        imageView.getStyleClass().add("product-image");
        loadProductImage(p, imageView);
        
        Button uploadImgBtn = createStyledButton("更换图片");
        uploadImgBtn.getStyleClass().add("small-button");
        uploadImgBtn.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择商品图片");
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg"));
            File file = fileChooser.showOpenDialog(primaryStage);
            if (file != null) {
                // 上传图片到服务器，获取服务器保存的文件名
                String serverFileName = shopController.uploadImage(file); 
                if (serverFileName != null) {
                    p.setImageUrl(serverFileName); // 设置为服务器文件名
                    loadProductImage(p, imageView); // 重新加载图片
                    // 可选：立即更新数据库中的图片路径
                    shopController.updateProduct(p);
                } else {
                    showAlert("错误", "图片上传失败", Alert.AlertType.ERROR);
                }
            }
        });
        
        imageBox.getChildren().addAll(imageView, uploadImgBtn);

        // 信息区域
        VBox infoBox = new VBox(8);
        infoBox.setPrefWidth(300);
        
        Label nameLabel = new Label(p.getPname());
        nameLabel.getStyleClass().add("product-name");
        
        // 表单布局
        GridPane formGrid = new GridPane();
        formGrid.setHgap(10);
        formGrid.setVgap(8);
        
        // 设置列约束，确保第二列可以扩展
        ColumnConstraints col1 = new ColumnConstraints();
        col1.setHgrow(Priority.NEVER);
        col1.setPrefWidth(45); // 固定标签宽度

        ColumnConstraints col2 = new ColumnConstraints();
        col2.setHgrow(Priority.ALWAYS); // 允许内容区域扩展
        col2.setFillWidth(true);

        formGrid.getColumnConstraints().addAll(col1, col2);
        
        Label priceLabel = new Label("价格:");
        priceLabel.getStyleClass().add("form-label");
        TextField priceField = new TextField(String.valueOf(p.getPrice()));
        priceField.getStyleClass().add("form-field");
        priceField.setPrefWidth(120);
        
        Label stockLabel = new Label("库存:");
        stockLabel.getStyleClass().add("form-label");
        TextField stockField = new TextField(String.valueOf(p.getStock()));
        stockField.getStyleClass().add("form-field");
        stockField.setPrefWidth(120);
        
        Label expireDateLabel = new Label("保质期:");
        expireDateLabel.getStyleClass().add("form-label");
        TextField expireDateField = new TextField(String.valueOf(p.getExpireDate())); 
        expireDateField.setEditable(false); // 只读
        expireDateField.getStyleClass().add("form-field");
        expireDateField.setPrefWidth(120);
        
        Label descLabel = new Label("描述:");
        descLabel.getStyleClass().add("form-label");
        TextArea descArea = new TextArea(p.getDesc());
        descArea.setPrefRowCount(2);
        descArea.setWrapText(true); // 允许文本换行
        descArea.getStyleClass().add("form-textarea");
        descArea.setPrefWidth(250); // 设置固定宽度，超出会自动换行
        
        // 复选框
        CheckBox statusCheck = new CheckBox("上架");
        statusCheck.setSelected(p.getStatus() == 1); // 上架时选中复选框
        statusCheck.getStyleClass().add("status-checkbox");
        
        CheckBox expireCheck = new CheckBox("临期");
        expireCheck.setSelected(p.getExpireSoon() == 1);
        expireCheck.getStyleClass().add("status-checkbox");
        
        // 根据商品类别设置临期复选框的可用性
        boolean isFoodOrDrink = "食物".equals(p.getCategory()) || "饮料".equals(p.getCategory());
        expireCheck.setDisable(!isFoodOrDrink); // 只有食品和饮料可以修改临期状态
        if (!isFoodOrDrink) {
            expireCheck.setTooltip(new Tooltip("只有食品和饮料类商品可以设置临期状态"));
        }
        
        CheckBox hotCheck = new CheckBox("热卖");
        hotCheck.setSelected(p.getHot() == 1);
        hotCheck.getStyleClass().add("status-checkbox");
        
        CheckBox newCheck = new CheckBox("上新");
        newCheck.setSelected(p.getNewP() == 1);
        newCheck.getStyleClass().add("status-checkbox");
        
        HBox statusBox = new HBox(15);
        statusBox.setAlignment(Pos.CENTER_LEFT);
        statusBox.getChildren().addAll(statusCheck, expireCheck, hotCheck, newCheck);
        
        formGrid.add(priceLabel, 0, 0);
        formGrid.add(priceField, 1, 0);
        formGrid.add(stockLabel, 0, 1);
        formGrid.add(stockField, 1, 1);
        formGrid.add(descLabel, 0, 2);
        formGrid.add(descArea, 1, 2);
        if ("食物".equals(p.getCategory()) || "饮料".equals(p.getCategory())) {
        	formGrid.add(expireDateLabel, 0, 3);
            formGrid.add(expireDateField, 1, 3);
            formGrid.add(statusBox, 0, 4, 2, 1);
        }
        else {
        	formGrid.add(statusBox, 0, 3, 2, 1);
        }
        
        infoBox.getChildren().addAll(nameLabel, formGrid);

        // 操作按钮区域
        VBox actionBox = new VBox(10);
        actionBox.setAlignment(Pos.TOP_CENTER);
        
        Button updateBtn = createStyledButton("保存更改");
        updateBtn.getStyleClass().add("primary-button");
        updateBtn.setOnAction(e -> {
            try {
                p.setPrice(Double.parseDouble(priceField.getText()));
                p.setStock(Integer.parseInt(stockField.getText()));
                p.setDesc(descArea.getText());
                p.setStatus(statusCheck.isSelected()? 1 : 0);
                p.setExpireSoon(expireCheck.isSelected() ? 1 : 0);
                p.setHot(hotCheck.isSelected() ? 1 : 0);
                p.setNewP(newCheck.isSelected() ? 1 : 0);
                
                boolean success = shopController.updateProduct(p);
                if (success) {
                    showAlert("成功", "商品更新成功", Alert.AlertType.INFORMATION);
                    loadProducts();
                } else {
                    showAlert("失败", "商品更新失败", Alert.AlertType.ERROR);
                }
            } catch (NumberFormatException ex) {
                showAlert("错误", "请输入有效的价格或库存数字", Alert.AlertType.WARNING);
            }
        });

        Button deleteBtn = createStyledButton("删除商品");
        deleteBtn.getStyleClass().add("danger-button");
        deleteBtn.setOnAction(e -> {
            Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
            confirmAlert.setTitle("确认删除");
            confirmAlert.setHeaderText("删除商品");
            confirmAlert.setContentText("确定要删除商品「" + p.getPname() + "」吗？此操作不可恢复。");
            
            confirmAlert.showAndWait().ifPresent(response -> {
                if (response == ButtonType.OK) {
                    boolean success = shopController.deleteProduct(p.getPid());
                    if (success) {
                        showAlert("成功", "商品删除成功", Alert.AlertType.INFORMATION);
                        loadProducts();
                    } else {
                        showAlert("失败", "商品删除失败", Alert.AlertType.ERROR);
                    }
                }
            });
        });
        
        actionBox.getChildren().addAll(updateBtn, deleteBtn);
        box.getChildren().addAll(imageBox, infoBox, actionBox);

        return box;
    }

    // ============ 图片处理功能 ============
    private void loadProductImage(Product p, ImageView imageView) {
        try {
            byte[] data = shopController.getProductImageBytes(p.getImageUrl());
            if (data != null) {
                InputStream is = new ByteArrayInputStream(data);
                Image img = new Image(is, imageView.getFitWidth(), imageView.getFitHeight(), true, true);
                imageView.setImage(img);
            } else {
                // 默认图
                imageView.setImage(new Image(getClass().getResource("/default.png").toString(),
                        imageView.getFitWidth(), imageView.getFitHeight(), true, true));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // ============ 提示对话框设计 ============
    // 弹窗提示
    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type, message, ButtonType.OK);
        alert.setHeaderText(title);
        alert.showAndWait();
    }

    // ============ 新增商品对话框设计 ============
    private void showAddProductDialog() {
        Stage dialog = new Stage();
        dialog.setTitle("新增商品");

        BorderPane dialogRoot = new BorderPane();
        dialogRoot.setPadding(new Insets(15));
        dialogRoot.getStyleClass().add("dialog-container");
        
        Label titleLabel = new Label("添加新商品");
        titleLabel.getStyleClass().add("dialog-title");
        BorderPane.setAlignment(titleLabel, Pos.CENTER);
        dialogRoot.setTop(titleLabel);

        GridPane formGrid = new GridPane();
        formGrid.setHgap(15);
        formGrid.setVgap(12);
        formGrid.setPadding(new Insets(15));

        // 表单字段
        Label nameLabel = new Label("商品名称:");
        nameLabel.getStyleClass().add("form-label");
        TextField nameField = new TextField();
        nameField.setPromptText("请输入商品名称");
        nameField.getStyleClass().add("form-field");
        
        Label priceLabel = new Label("价格:");
        priceLabel.getStyleClass().add("form-label");
        TextField priceField = new TextField();
        priceField.setPromptText("0.00");
        priceField.getStyleClass().add("form-field");
        
        Label stockLabel = new Label("库存:");
        stockLabel.getStyleClass().add("form-label");
        TextField stockField = new TextField();
        stockField.setPromptText("0");
        stockField.getStyleClass().add("form-field");
        
        Label descLabel = new Label("描述:");
        descLabel.getStyleClass().add("form-label");
        TextArea descArea = new TextArea();
        descArea.setPromptText("请输入商品描述");
        descArea.setPrefRowCount(3);
        descArea.getStyleClass().add("form-textarea");
        
        Label categoryLabel = new Label("类别:");
        categoryLabel.getStyleClass().add("form-label");
        ComboBox<String> categoryCombo = new ComboBox<>();
        categoryCombo.getItems().addAll("食物", "饮料", "文具", "日用品");
        categoryCombo.setValue("食物"); // 默认选中
        categoryCombo.getStyleClass().add("form-field");
        
        Label expireDateLabel = new Label("保质期:");
        expireDateLabel.getStyleClass().add("form-label");
        TextField expireDateField = new TextField();
        expireDateField.setPromptText("yyyy/MM/dd");
        expireDateField.getStyleClass().add("form-field");

        CheckBox statusCheck = new CheckBox("上架");
        statusCheck.setSelected(true);
        statusCheck.getStyleClass().add("status-checkbox");

        CheckBox hotCheck = new CheckBox("热卖");
        hotCheck.setSelected(false);
        hotCheck.getStyleClass().add("status-checkbox");
        
        CheckBox newCheck = new CheckBox("上新");
        newCheck.setSelected(true);
        newCheck.getStyleClass().add("status-checkbox");
        
        CheckBox expireCheck = new CheckBox("临期");
        expireCheck.setSelected(false);
        expireCheck.getStyleClass().add("status-checkbox");
        
        HBox tagsBox = new HBox(15, statusCheck, hotCheck, newCheck, expireCheck);
        
        
        final File[] selectedFile = new File[1];
        Label imageLabel = new Label("图片:");
        imageLabel.getStyleClass().add("form-label");
        HBox imageBox = new HBox(10);
        imageBox.setAlignment(Pos.CENTER_LEFT);
        
        Label fileNameLabel = new Label("未选择文件");
        fileNameLabel.getStyleClass().add("file-name-label");
        
        Button chooseImgBtn = createStyledButton("选择图片");
        chooseImgBtn.getStyleClass().add("small-button");
        chooseImgBtn.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择商品图片");
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg"));
            File file = fileChooser.showOpenDialog(dialog);
            if (file != null) {
                selectedFile[0] = file;
                fileNameLabel.setText(file.getAbsolutePath());
            }
        });
        
        imageBox.getChildren().addAll(chooseImgBtn, fileNameLabel);

        // 添加表单元素到网格
        formGrid.add(nameLabel, 0, 0);
        formGrid.add(nameField, 1, 0);
        formGrid.add(priceLabel, 0, 1);
        formGrid.add(priceField, 1, 1);
        formGrid.add(stockLabel, 0, 2);
        formGrid.add(stockField, 1, 2);
        formGrid.add(descLabel, 0, 3);
        formGrid.add(descArea, 1, 3);
        formGrid.add(categoryLabel, 0, 4);
        formGrid.add(categoryCombo, 1, 4);
        formGrid.add(expireDateLabel, 0, 5);
        formGrid.add(expireDateField, 1, 5);
        formGrid.add(imageLabel, 0, 6);
        formGrid.add(imageBox, 1, 6);
        formGrid.add(tagsBox, 1, 7);
        
        dialogRoot.setCenter(formGrid);

        // 底部按钮区域
        HBox buttonBox = new HBox(15);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        buttonBox.setPadding(new Insets(15, 0, 0, 0));
        
        Button cancelBtn = createStyledButton("取消");
        cancelBtn.getStyleClass().add("secondary-button");
        cancelBtn.setOnAction(e -> dialog.close());
        
        Button addBtn = createStyledButton("添加商品");
        addBtn.getStyleClass().add("primary-button");
        addBtn.setOnAction(e -> {
            try {
                if (nameField.getText().isEmpty()) {
                    showAlert("错误", "请输入商品名称", Alert.AlertType.WARNING);
                    return;
                }
                
                Product p = new Product();
                p.setPname(nameField.getText());
                p.setPrice(Double.parseDouble(priceField.getText()));
                p.setStock(Integer.parseInt(stockField.getText()));
                p.setDesc(descArea.getText());
                p.setCategory(categoryCombo.getValue());
                p.setExpireDate(expireDateField.getText());
                p.setStatus(statusCheck.isSelected()? 1 : 0);
                p.setHot(hotCheck.isSelected()? 1 : 0);
                p.setNewP(newCheck.isSelected()? 1 : 0);
                p.setExpireSoon(expireCheck.isSelected()? 1 : 0);
                
                boolean success = shopController.addProduct(p, selectedFile[0]); 
                if (success) {
                    showAlert("成功", "商品添加成功", Alert.AlertType.INFORMATION);
                    loadProducts();
                    dialog.close();
                } else {
                    showAlert("失败", "商品添加失败", Alert.AlertType.ERROR);
                }
            } catch (NumberFormatException ex) {
                showAlert("错误", "请输入有效的价格或库存数字", Alert.AlertType.WARNING);
            }
        });
        
        buttonBox.getChildren().addAll(cancelBtn, addBtn);
        dialogRoot.setBottom(buttonBox);

        Scene scene = new Scene(dialogRoot, 500, 550);
        scene.getStylesheets().add(
                getClass().getResource("/css/style.css").toExternalForm()
        );
        dialog.setScene(scene);
        dialog.show();
    }

    public void back() throws IOException {
        // 获取当前登录窗口的Stage
        Stage adminMainStage = (Stage) backBtn.getScene().getWindow();

        AdminMainFrame adminMainFrame = new AdminMainFrame();
        adminMainFrame.setUser(user.getId(),user.getPassword(),user.getRole());

        Stage stage = new Stage();
        adminMainFrame.show(stage);

        adminMainStage.close();
    }

}